﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Timers;

namespace WebMonitorService
{
    public partial class Service1 : ServiceBase
    {
        private Timer _timer;
        private string _logFilePath;
        private string _url;
        private int _interval;

        public Service1()
        {
            InitializeComponent();
            LoadConfiguration();
        }

        private void LoadConfiguration()
        {
            _url = ConfigurationManager.AppSettings["Url"];
            _interval = int.Parse(ConfigurationManager.AppSettings["Interval"]);
            _logFilePath = ConfigurationManager.AppSettings["LogFilePath"];
        }

        protected override void OnStart(string[] args)
        {
            _timer = new Timer(_interval*1000);
            _timer.Elapsed += OnTimerElapsed;
            _timer.AutoReset = true;
            _timer.Enabled = true;
            Log("Service started.");
        }

        protected override void OnStop()
        {
            _timer.Enabled = false;
            Log("Service stopped.");
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                var stopwatch = Stopwatch.StartNew();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
                request.Method = "GET";

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    stopwatch.Stop();
                    Log($"URL: {_url}, Status: {response.StatusCode}, ResponseTime: {stopwatch.ElapsedMilliseconds}ms");
                }
            }
            catch (Exception ex)
            {
                Log($"Error: {ex.Message}");
            }
        }

        private void Log(string message)
        {
            File.AppendAllText(_logFilePath, $"{DateTime.Now}: {message}{Environment.NewLine}");
        }
    }
}